package com.zcah.common.exception;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.zcah.common.domain.LogDO;
import com.zcah.common.service.LogService;
import com.zcah.common.vo.R;
import com.zcah.system.domain.JwtuserDO;

/**
 * 异常处理器
 */
@RestControllerAdvice
public class BDExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	LogService logService;
	
    // 捕捉UnauthorizedException
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public R handle401() {
        return R.error(401, "Unauthorized");
    }
	
    // 捕捉shiro的异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public R handle401(ShiroException e) {
        return R.error(401, e.getMessage());
    }

	@ExceptionHandler({ Exception.class })
	public Object handleException(Exception e, HttpServletRequest request) {
		LogDO logDO = new LogDO();
		logDO.setGmtCreate(new Date());
		logDO.setOperation("error");
		logDO.setMethod(request.getRequestURL().toString());
		logDO.setParams(e.toString());
		// UserDO current = ShiroUtils.getUser();
		JwtuserDO current = new JwtuserDO();
		//TODO 使用Shiro用户权限管理
		if (null != current) {
			logDO.setUserId(current.getId());
			logDO.setUsername(current.getUsername());
		}
		logService.save(logDO);
		logger.error(e.getMessage(), e);
		return R.error(500, "服务器错误，请联系管理员");
	}
}
